package cn.hchaojie.boot.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hchaojie.boot.domain.AjaxResult;
import cn.hchaojie.boot.security.JwtTokenProvider;

@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
	@Autowired
	private JwtTokenProvider tokenProvider;
	
	@Autowired
	private ObjectMapper mapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		AjaxResult result = new AjaxResult("200", "登陆成功！");
		
		// 登陆成功后，往响应头里面写入token
		tokenProvider.insertAuthenticationToken(response, authentication);
		
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(mapper.writeValueAsString(result));
	}

}
